import json
import logging
import random
from django.http import JsonResponse, HttpResponse

from ihome.libs.captcha.captcha import captcha
from ihome.libs.yuntongxun.ccp_sms import CCP

logger = logging.getLogger()
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms

# Create your views here.


# 图形验证码接口
class ImageCode(View):


    def get(self, request, *args, **kwargs):

        # 1.调用库生成图形验证码
        text, image = captcha.generate_captcha()

        # 2.创建连接到redis的对象
        conn = get_redis_connection('verify_code')

        # 3.提取cur参数
        cur = request.GET.get('cur')

        try:
            # 把验证码写入redis
            conn.setex(
                'img_%s' % cur,
                300,
                text
            )
        except Exception as e:
            print(e)
            logger.error(e)

        # 构建响应数据。返回验证码图片
        return HttpResponse(image, content_type='image/jpg')


# SMS手机验证码
class SMSCode(View):


    def post(self,request):
        # 提取参数
        data = json.loads(request.body.decode())
        # print(data)

        mobile = data.get('mobile')
        id = data.get('id')
        text_client = data.get('text')
        print(mobile)
        print(id)
        print(text_client)

        # 创建连接到redis的对象
        conn = get_redis_connection('verify_code')


        # 提取图形验证码
        text_server = conn.get('img_%s' % id)

        if text_server is None:
            # 图形验证码过去或不存在
            return JsonResponse({'errno': 4002, 'errmsg': '图形验证码失效'})

        # 删除图形验证码
        try :
            conn.delete('img_%s' % id)
        except Exception as e:
            print(e)


        # 对比图形验证码
        text_server = text_server.decode()

        if text_client.lower() != text_server.lower():
            return JsonResponse({'errno': 4004, 'errmsg': '图形验证码错误'})


        # 创建发送短信的redis连接对象
        sms_conn = get_redis_connection('sms_code')

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print('短信验证码：%s' % sms_code)

        # 创建管道对象
        p1 = sms_conn.pipeline()

        # 保存短信验证码
        p1.setex('sms_%s' % mobile, 300, sms_code)

        # 标记已发送
        p1.setex('flag_%s' % mobile, 60, 1)

        # 管道执行提交
        p1.execute()

        # 异步调用发送短信
        send_sms.delay(mobile, sms_code)



        return JsonResponse({'errno': 0, "errmsg": '发送成功'})